﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public enum ViewUIType{
	NGUI,
	UGUI,
}
public class ViewUIMgr : ModuleComponent<ViewUIMgr> {
	ViewUIType uitype = ViewUIType.NGUI;
	private Dictionary<string,ViewUI> showViewList = new Dictionary<string,ViewUI>();
	private ViewUI[] showViewWithDepth;
	public Transform Root;

	public Type ShowViewUI<Type>(ViewUIPanelDepth depth,string otherPath = ""){
		if(showViewWithDepth == null)
			showViewWithDepth = new ViewUI[(int)ViewUIPanelDepth.Count];
		Type view;
		ViewUI viewui;
		string viewname = typeof(Type).Name;
		int intdepth = (int)depth;
		if (!showViewList.ContainsKey (viewname)) {
			checkRoot ();
			if (otherPath == "")
				otherPath = BaseModel.Instance.ModueName;
			otherPath += "/";
			GameObject obj = ObjManager.Instance.AddChild (ObjManager.Instance.PathUIPanel + otherPath, viewname, Root, ObjManager.Instance.ParentUI);
			view = obj.GetComponent<Type> ();
			viewui = view as ViewUI;
			showViewList.Add (viewname, viewui);
			viewui.Init ();
		} else
			viewui = showViewList [viewname];

		if (showViewWithDepth [intdepth] == viewui) {
			//目标层级界面就是当前界面 直接返回
			return viewui.GetComponent<Type>();
		} else {
			//目标层级界面不是展示界面 则关闭目标层级往上各个界面
			CloseView (intdepth);
			viewui.gameObject.SetActive (true);
			UIPanel panel = viewui.GetComponent<UIPanel> ();
			panel.depth = intdepth;
			showViewWithDepth[intdepth] = viewui;
			viewui.nowDepth = intdepth;
			viewui.Open ();
		}
		view = viewui.GetComponent<Type> ();
		return view;
	}
	void CloseView(int depth){
		int count = (int)ViewUIPanelDepth.Count;
		for (int i = depth; i < count; i++) {
			if (showViewWithDepth [i] != null) {
				Debug.Log("Close +"+showViewWithDepth[i].gameObject.name);
				showViewWithDepth[i].gameObject.SetActive (false);
				showViewWithDepth [i] = null;
			}
		}
	}
	public Type GetViewUI<Type>(){
		string viewname;
		viewname = (typeof(Type).Name);
		if (!showViewList.ContainsKey (viewname)) {
			return ShowViewUI<Type> (ViewUIPanelDepth.Down); 
		}
		return showViewList [viewname].GetComponent<Type>();
	}
	public void Close<Type>(){
		string viewname = typeof(Type).Name;
		if (showViewList.ContainsKey (viewname) && showViewList [viewname].gameObject.activeSelf == true)
			CloseView (showViewList [viewname].nowDepth);
	}
	public void CloseAll(){
		for (int i = 0,count = (int)ViewUIPanelDepth.Count; i < count; i++) {
			CloseView (i);
		}
	}
	public void Close<Type>(ViewUI view){

		CloseView (view.nowDepth);
	}
	public void Close(ViewUIPanelDepth depth){
		CloseView ((int)depth);
	}
	private void checkRoot(){
		if (Root == null) {
			switch(uitype){
			case ViewUIType.NGUI:
				Root = ObjManager.Instance.AddChild("ModulePrefab/","UI Root",transform).transform;
				break;
			}
		}
	}
}
